package com.yexiao.cofe.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yexiao.cofe.business.mapper.PermissionMapper;
import com.yexiao.cofe.business.mapper.RoleMapper;
import com.yexiao.cofe.business.mapper.RolePermissionMapper;
import com.yexiao.cofe.business.mapper.UserRoleMapper;
import com.yexiao.cofe.business.pojo.Permission;
import com.yexiao.cofe.business.pojo.Role;
import com.yexiao.cofe.business.pojo.RolePermission;
import com.yexiao.cofe.business.pojo.UserRole;
import com.yexiao.cofe.business.service.RoleService;
import com.yexiao.cofe.common.exception.BusinessException;
import com.yexiao.cofe.util.SystemUtil;
import com.yexiao.core.util.JSONUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lkl
 * @since 2025/4/8
 */
@Service
public class RoleServiceImpl implements RoleService {
    
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public void addRole(JSONObject param, String token) {
        String roleName = JSONUtil.checkAndGetStr(param, "roleName");
        Integer sort = JSONUtil.getIntDef(param, 0, "sort");

        Role temp = roleMapper.selectRoleByRoleName(roleName);
        if(temp != null){
            throw new BusinessException("角色名重复");
        }

        Role role = new Role(roleName, sort);
        roleMapper.insert(role);
    }

    @Override
    public void deleteRoleById(Integer roleId) {
        List<UserRole> userRoleList = userRoleMapper.selectByRoleId(roleId);
        if(CollectionUtil.isNotEmpty(userRoleList)){
            throw new BusinessException("角色正在使用，无法删除");
        }

        roleMapper.deleteById(roleId);
        rolePermissionMapper.deletePermissionByRoleId(roleId);
    }

    @Override
    public void updateRole(JSONObject param, String token) {
        Integer roleId = JSONUtil.checkAndGetInt(param, "roleId");
        String name = JSONUtil.getStr(param, "roleName");
        Integer sort = JSONUtil.getInt(param, "sort");

        roleMapper.update(roleId, name, sort);
    }

    @Override
    public JSONObject search(JSONObject param, String token) {
        String name = JSONUtil.getStr(param, "name");
        Integer pageSize = JSONUtil.checkAndGetInt(param, "pageSize");
        Integer pageNum = JSONUtil.checkAndGetInt(param, "pageNum");

        PageHelper.startPage(pageNum, pageSize);
        List<Role> roleList = roleMapper.listRole(name);
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);

        return JSONUtil.of(
                "list", roleList,
                "pageNum", pageInfo.getPageNum(),
                "pageSize", pageInfo.getPageSize(),
                "total", pageInfo.getTotal()
        );
    }

    @Override
    public void bindPermission(JSONObject param, String token) {
        Integer roleId = JSONUtil.checkAndGetInt(param, "roleId");
        List<String> permissionIdList = JSONUtil.getList(param, String.class, "permissionIdList");

        rolePermissionMapper.deletePermissionByRoleId(roleId);

        Role role = roleMapper.selectById(roleId);
        SystemUtil.checkErrorIfNull(role, "角色不存在");

        List<Permission> permissionList = listPermission(permissionIdList);
        Set<String> permissionIdSet = permissionList.stream().map(Permission::getPermissionId).collect(Collectors.toSet());

        for (String permissionId : permissionIdSet) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionMapper.insert(rolePermission);
        }
    }

    @Override
    public JSONObject detail(JSONObject param, String token) {
        Integer roleId = JSONUtil.checkAndGetInt(param, "roleId");
        Role role = roleMapper.selectById(roleId);
        SystemUtil.checkErrorIfNull(role, "角色不存在");

        List<Permission> permissionList = permissionMapper.listByRoleId(roleId);
        List<JSONObject> permissionResList = new ArrayList<>();
        for (Permission permission : permissionList) {
            permissionResList.add(permission.getBaseMsg());
        }

        return JSONUtil.of(
                "roleId", roleId,
                "roleName", role.getRoleName(),
                "sort", role.getSort(),
                "permissionList", permissionResList
        );
    }

    private List<Permission> listPermission(List<String> permissionIdList) {
        if(CollectionUtil.isEmpty(permissionIdList)){
            return new ArrayList<>();
        }

        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(Permission.PERMISSION_ID, permissionIdList);
        return permissionMapper.selectList(queryWrapper);
    }
}
